<?php

namespace app\admin\controller\store;

use app\common\controller\Backend;
use app\common\model\Store as ModelStore;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Store extends Backend
{
    protected $multiFields = 'is_show';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Store');
    }
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(['id', 'name'], false);
            $total = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            foreach($list as &$item){
//                $pro_ids = explode(",", $item['pro_id']);
                $pro_ids = model('ProductStore')->where('store_id',$item['id'])->column('pro_id');
                $pro_arr = [];
                foreach($pro_ids as $v){
                    $product = model('Product')->where('id',$v)->field('title,cate_id')->find();
                    array_push($pro_arr,$product['title']);
                }
                $item['product'] = implode(" | ",$pro_arr);

                $cate_ids =  model('ProductCate')->where('pro_id', "in", $pro_ids)->group('cate_id')->column('cate_id');
//                $cate_ids = explode(",", $item['cate_id']);
                $cate_arr = [];
                foreach($cate_ids as $v){
                    $cate = model('StoreCate')->where('id',$v)->find();
                    array_push($cate_arr,$cate['name']);
                }
                $item['cate'] = implode(" | ",$cate_arr);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $result = false;
                Db::startTrans();
                try {
//                    $pro_ids = $params['pro_id'] ? explode(",",$params['pro_id']) : [];
//                    $cate_ids = [];
//                    foreach($pro_ids as $item){
//                        if(model('ProductStore')->where('pro_id',$item)->count())
//                            throw new Exception("项目id: ".$item." 已被其他合作商绑定");
//                        $product = model('Product')->where('id',$item)->find();
//                        $cate_id = explode(",",$product['cate_id']);
//                        foreach($cate_id as $value){
//                            if(!in_array($value,$cate_ids)){
//                                array_push($cate_ids,$value);
//                            }
//                        }
//                    }
//                    $params['cate_id'] = implode(",",$cate_ids);
                    $this->model->validateFailException(true)->validate('app\common\validate\Store.add');
                    $result = $this->model->allowField(true)->save($params);
//                    foreach($pro_ids as $v){
//                        model('ProductStore')->create(['store_id'=>$result['id'],'pro_id'=>$v]);
//                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        } else {
//            $this->assign('cateList', $this->getCateList());
        }
        return $this->view->fetch();
    }
    public function edit($ids = '')
    {
        $row = $this->model->get($ids);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
//                    $pro_ids = $params['pro_id'] ? explode(",",$params['pro_id']) : [];
//                    $cate_ids = [];
//                    foreach($pro_ids as $item){
//                        if(model('ProductStore')->where('pro_id',$item)->where('store_id','neq',$ids)->count())
//                            throw new Exception("项目id: ".$item." 已被其他合作商绑定");
//                        $product = model('Product')->where('id',$item)->find();
//                        $cate_id = explode(",",$product['cate_id']);
//                        foreach($cate_id as $value){
//                            if(!in_array($value,$cate_ids)){
//                                array_push($cate_ids,$value);
//                            }
//                        }
//                    }
//                    $params['cate_id'] = implode(",",$cate_ids);
                    $row->validateFailException(true)->validate('app\common\validate\Store.edit');
                    $result = $row->allowField(true)->save($params);
//                    model('ProductStore')->where('store_id',$ids)->delete();
//                    foreach($pro_ids as $v){
//                        model('ProductStore')->create(['store_id'=>$ids,'pro_id'=>$v]);
//                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        } else {
//            $this->assign('cateList', $this->getCateList());
            $pro_ids = model('ProductStore')->where('store_id',$ids)->column('pro_id');
            $this->view->assign("pro_ids", implode(",",$pro_ids));
            $this->view->assign("row", $row);
        }
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = '')
    {
        parent::del($ids);
    }

    public function ProductSelect(){
        $keyword = $this->request->param('title');
        $where = [];
        if($this->request->request("keyValue")){
            $ids = explode(",",$this->request->request("keyValue"));
            $where['id'] = ['in',$ids];
        }
        if($keyword){
            $where['title'] = ['like',"%$keyword%"];
        }
        $product = model('product')->where($where)->order('weigh desc,id desc')->field(['id', 'title'])->select();
        foreach($product as $item){
            $item['title'] = $item['title']."(id: ".$item['id'].")";
        }
        return json(['list' => $product, 'total' => count($product)]);
    }

    protected function getCateList()
    {
        $list = model('StoreCate')->order('weigh desc, id desc')->column('id,name');
        return $list;
    }
}
